#include "xftp_list.hpp"
#include <glog/logging.h>

#include <event2/event.h>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <event2/bufferevent_struct.h>
#include <string>
xftp_list::xftp_list(/* args */)
{
}

xftp_list::~xftp_list()
{
}
void xftp_list::write_cb(struct bufferevent* buffer,void *arg)
{
    VLOG(0)<<"========================";
    xftp_list* x = reinterpret_cast<xftp_list*>(arg);
    x->recv_cmd("226 Transfer complete\r\n");
}
void xftp_list::parse_cmd(std::string cmd,std::string msg)
{
    std::string recv_msg = "";
    if(cmd == "PWD")
    {
        VLOG(0)<<"parse cmd = "<<cmd;
        // 记录当前路径，上传下载删除都要使用
        recv_msg = "257 \"";
		recv_msg += m_cmd_task->m_master_dir;
		recv_msg += "\" is current dir.\r\n";
        recv_cmd(recv_msg);
    }
    else if(cmd =="LIST")
    {
        VLOG(0)<<"cmd = "<<cmd;
        if (ip.empty() || port <= 0 || !base)
        {
            VLOG(0) << "ConnectPORT failed ip or port or base is null";
            return;
        }
        
        
        
        if(this->recv_bffer)
        {
            bufferevent_free(recv_bffer);
            recv_bffer = NULL;
        }
        if(base == NULL)
        {
            VLOG(0)<<"base error";
            return;
        }
        recv_bffer = bufferevent_socket_new(base,-1,BEV_OPT_CLOSE_ON_FREE);
        if(recv_bffer == NULL)
        {
            VLOG(0)<<"bev error";
            return;
        }
        sockaddr_in sin;
        memset(&sin, 0, sizeof(sin));
        sin.sin_family = AF_INET;
        sin.sin_port = htons(port);
        evutil_inet_pton(AF_INET, ip.c_str(), &sin.sin_addr.s_addr);
        //设置回调和权限
        bufferevent_setcb(recv_bffer, 0, xftp_list::write_cb, 0, this);
	    bufferevent_enable(recv_bffer, EV_READ | EV_WRITE);
        //添加超时 
        timeval rt = { 60,0 };
        bufferevent_set_timeouts(recv_bffer, &rt, 0);
        bufferevent_socket_connect(recv_bffer, (sockaddr*)&sin, sizeof(sin));

        recv_cmd("150 Here comes the directory listing.\r\n");
        std::string list = "-rw-rw-r--  1 chen chen   64463 Dec  8 12:00 101.jpg";
        bufferevent_write(recv_bffer,list.c_str(),list.size());

        
    }
}